package com.demo.flowcontroller.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.demo.flowcontroller.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {
    private static final String RESOURCE_NAME = "test";
    private static final String USER_RESOURCE_NAME = "test";
    private  static final String DEGRADE_RESOURCE_NAME = "degrade";

    @RequestMapping("/test")
    @SentinelResource(value = USER_RESOURCE_NAME, blockHandler = "blockHandlerAction")
    public User getuser(){
        return new User("frank","28");
    }

    public User blockHandlerAction(BlockException exception){
        exception.printStackTrace();
        return new User("流控状态",null);
    }
    /**
     * 定义规则
     *
     * spring 的初始化方法
     */
    @PostConstruct
    public static void initFlowController(){
        // 流控规则
        List<FlowRule> rules = new ArrayList<>();
        // 流控
        FlowRule rule = new FlowRule();
        // 设置对应流控资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置资源保护阈值 1次/s
        rule.setCount(1);
        // 添加规则
        rules.add(rule);
        // 加载规则
        FlowRuleManager.loadRules(rules);
    }
}
